package org.bspv.pharma.dao.impl;

import java.util.LinkedList;
import java.util.List;

import org.bspv.pharma.dao.OrderDAO;
import org.bspv.pharma.model.Drugstore;
import org.bspv.pharma.model.Order;
import org.bspv.pharma.model.Order.OrderStateEnum;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository(value = "orderDAO")
public class OrderDAOImpl extends AbstractHibernateDAO<Order, Long> implements OrderDAO {

    /**
     * Nombre maximum de commandes récentes à remonter.
     */
    public static final int NB_RECENT_ORDERS = 5;

    @Autowired
    public OrderDAOImpl(SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Order> findOrders() {
        DetachedCriteria crit = DetachedCriteria.forClass(getManagedType());
        List<OrderStateEnum> states = new LinkedList<OrderStateEnum>();
        states.add(OrderStateEnum.ENCOURS);
        states.add(OrderStateEnum.ENVOYEE);
        states.add(OrderStateEnum.PARTIELLE);
        states.add(OrderStateEnum.ENRECEPTION);
        crit.add(Restrictions.in("state", states));
        return getHibernateTemplate().findByCriteria(crit);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Order> findRecentOrders() {
        DetachedCriteria crit = DetachedCriteria.forClass(getManagedType());
        crit.add(Restrictions.eq("state", OrderStateEnum.TERMINEE));
        crit.addOrder(org.hibernate.criterion.Order.desc("date"));
        return getHibernateTemplate().findByCriteria(crit, 0, NB_RECENT_ORDERS);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Order> findCurrentOrders(Drugstore drugstore) {
        DetachedCriteria crit = DetachedCriteria.forClass(getManagedType());
        crit.add(Restrictions.eq("state", OrderStateEnum.ENCOURS));
        crit.add(Restrictions.eq("drugstore", drugstore));
        crit.addOrder(org.hibernate.criterion.Order.desc("date"));
        return getHibernateTemplate().findByCriteria(crit);
    }

}
